<?php

namespace App\Http\Requests\UserCenter;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\User;
use Auth;

class ChangeNameRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    public function addValidator()
    {
        //验证此用户名是否已存在
        Validator::extend('name_is_had', function ($attribute, $value, $parameters, $validator) {
            $user = Auth::user();
            $count = User::where('name', $value)
                ->where('id','<>',$user->id)
                ->count();
            if ($count > 0) {
                return false;
            } else {
                return true;
            }
        });
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
            $this->addValidator();
        return [
            'username' => [
                'sometimes',
                'required',
                'between:4,16',
                'regex:/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u',
                'name_is_had',
            ],
        ];
    }

    public function messages()
    {
        return [
            'username.required' =>'用户名不能为空',
            'username.between' =>'用户名长度只能在4-16个字符之间',
            'username.regex' =>'用户名只能由 汉字 字母 数字 下划线 组成',
            'username.name_is_had' => '用户名已存在',
        ];
    }

    public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        throw (new HttpResponseException(response()->json([
            'status_code' => 500,
            'error' => $validator->errors()->all(),
        ], 200)));
    }
}
